import Axios, { AxiosResponse } from 'axios';
import { notification } from 'antd';

export type AxiosResFormat<T> = Promise<AxiosResponse<ResponseFormat<T>>>;
export interface ResponseFormat<T = any> {
	msg: string;
	data: T;
	error_code: number;
}

export interface ApiResBase<T = any> {
	msg: string;
	data: T;
	code: number;
}

export type ApiFormat<T> = Promise<T>;

const axios = Axios.create({
	baseURL: process.env.REACT_APP_BASEAPI || '/',
	// baseURL: '/',
	timeout: 60000,
	withCredentials: true,
	responseType: 'json',
});
export default axios;

// 请求拦截器
axios.interceptors.request.use(
	(config) => {
		// Do something before request is sent
		return config;
	},
	(error) => {
		// Do something with request error
		return Promise.reject(error);
	},
);

// 响应拦截器
axios.interceptors.response.use(
	(response) => {
		const { data } = response;
		return data;
		// const errMsg = `服务器忙碌，${data.msg}`;
		// notification.error({ message: errMsg, duration: 2 });
		// throw new Error(`服务器忙碌，${data.msg}`);
	},
	(error) => {
		// Any status codes that falls outside the range of 2xx cause this function to trigger
		// Do something with response error
		// if (error.response && error.response.status === 401) {
		//  window.location.href = '';
		// }
		console.log('response err', error);
		return Promise.reject(error.response);
	},
);

export function getParam(name: string): string | number | undefined {
	const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
	const location: Location = window.location;
	const href = location.href;
	const query = href.substr(href.lastIndexOf('?') + 1);
	const res = query.match(reg);
	if (res !== null) {
		return decodeURIComponent(res[2]);
	}
	return undefined;
}
